<template>
  <div>
    <h1>下载功能：</h1>
    <div class="part part-1">
      <h2>a标签实现</h2>
    </div>

    <div class="part part-2">
      <h2>window.open实现</h2>
      <input type="file" ref="file">
      <br>
      <button @click="downloadByWindowOpen">下载</button>
    </div>

    <div class="part part-3">
      文件对象转blob流。
      <input type="file" ref="file3">
      <br>
      <el-button @click="downloadByBlob">blob流下载</el-button>
      <el-button @click="downloadByUrl">url流下载</el-button>
    </div>
  </div>
</template>

<script>
  import axios from 'axios'
  export default {
    name: "download",
    methods: {
      downloadByWindowOpen() {
        const file = this.$refs.file.files[0];
        console.log(file);

        const url = window.URL.createObjectURL(file);
        window.open(url)
      },

      downloadByBlob() {
        const file = this.$refs.file3.files[0];
        const reader = new FileReader();
        reader.readAsArrayBuffer(file);
        reader.onload = _ => {
          console.log(_);
          const blob = new Blob([file]);
          console.log(blob);
        }
        console.log(file);
        debugger
        const blob = new Blob([file], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
        if (window.navigator.msSaveOrOpenBlob) {
          // ie10以上包含10，支持window.navigator.msSaveOrOpenBlob
          navigator.msSaveBlob(blob);
        } else {
          let a = document.createElement('a');
          a.href = window.URL.createObjectURL(blob);
          a.download = `${new Date().getTime()}.zip`;
          a.click();

          // 释放内存
          window.URL.revokeObjectURL(a.href);
          a = null;
        }
      },

      downloadByUrl() {
        let url = 'http://downza.91speed.vip/2022/07/15/douyin.apk?timestamp=62da14df&auth_key=ccd0b63ff465d938c64555ec620dcfe8&sign=b92b94dc97cd97083c5d2884016449a0&t=62da22ef'
        const res = axios.get(url, '', {
          responseType: 'blob',
          timeout: 300000
        });

        console.log(res);
        const blob = new Blob([res.data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'});
        if (window.navigator.msSaveOrOpenBlob) {
          // ie10以上包含10，支持window.navigator.msSaveOrOpenBlob
          navigator.msSaveBlob(blob);
        } else {
          let a = document.createElement('a');
          a.href = window.URL.createObjectURL(blob);
          a.download = `${new Date().getTime()}.apk`;
          a.click();

          // 释放内存
          window.URL.revokeObjectURL(a.href);
          a = null;
        }
      }
    }
  }
</script>

<style scoped>

</style>
